package com.lxt.controller;

import com.lxt.common.HttpResult;
import com.lxt.common.util.JsonUtils;
import com.lxt.common.util.MD5Utils;
import com.lxt.common.util.RedisOperator;
import com.lxt.pojo.Users;
import com.lxt.pojo.VO.UsersVO;
import com.lxt.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author IvXuTao
 * @Package com.lxt.controller
 * @date 2022/4/21 16:40
 */

@Controller
public class SSOController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisOperator redisOperator;

    public static final String REDIS_USER_TOKEN = "redis_user_token";
    public static final String REDIS_USER_TICKET = "redis_user_ticket";
    public static final String REDIS_TMP_TICKET = "redis_tmp_ticket";
    public static final String COOKIE_USER_TICKET = "cookie_user_ticket";

    @GetMapping("/login")
    public String login(String returnUrl,
                        Model model,
                        HttpServletRequest request,
                        HttpServletResponse response) {

        model.addAttribute("returnUrl", returnUrl);

        //1.获取userTicket门票，如果cookie中能够获取到证明用户登陆过，此时签发一个一次性临时票据并且回跳
        String userTicket = getCookie(COOKIE_USER_TICKET, request);
        boolean isVerified = verifyUserTicket(userTicket);
        if (isVerified) {
            String tmpTicket = createTmpTicket();
            return "redirect:" + returnUrl + "?tmpTicket=" + tmpTicket;
        }

        // 2. 用户从未登录过，第一次进入则跳转到CAS的统一登录页面
        return "login";
    }

    /**
     * 校验CAS全局门票
     *
     * @param userTicket
     * @return
     */
    private boolean verifyUserTicket(String userTicket) {

        //0.验证CAS门票不能为空
        if (StringUtils.isBlank(userTicket)) {
            return false;
        }

        //1.验证并且获取userTicket
        String userId = redisOperator.get(REDIS_USER_TICKET + ":" + userTicket);
        if (StringUtils.isBlank(userId)) {
            return false;
        }

        //2.验证门票对应的user会话是否存在
        String userRedis = redisOperator.get(REDIS_USER_TICKET + ":" + userId);
        if (StringUtils.isBlank(userRedis)) {
            return false;
        }


        return true;
    }

    /**
     * CAS的统一登陆接口
     * 目的：
     * 1.登陆后创建用户的全局会话                  ->  uniqueToken
     * 2.创建用户全局门票，用于表示在CAS端是否登录    ->  userTicket
     * 3.创建用户的临时票据，用于回跳回传            ->  tmpTicket
     */
    @PostMapping("/doLogin")
    public String doLogin(String username,
                          String password,
                          String returnUrl,
                          Model model,
                          HttpServletRequest request,
                          HttpServletResponse response) throws Exception {
        model.addAttribute("returnUrl", returnUrl);

        //0.判断用户名和密码不为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            model.addAttribute("errmsg", "用户名或密码不能为空");
            return "login";
        }

        //1.实现登陆查询
        Users user = userService.queryUserForLogin(username,
                //数据库存储的是加密后的密码，所以需要进行加密后比较
                MD5Utils.getMD5Str24(password));

        if (user == null) {
            model.addAttribute("errmsg", "用户名或密码不正确");
            return "login";
        }

        //2.实现用户的redis会话
        String uniqueToken = UUID.randomUUID().toString().trim();
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(user, usersVO);
        usersVO.setUserUniqueToken(uniqueToken);
        redisOperator.set(REDIS_USER_TOKEN + ":" + user.getId(),
                JsonUtils.objectToJson(usersVO));

        //3.生成ticket门票，全局门票，代表用户在CAS端登陆过
        String userTicket = UUID.randomUUID().toString().trim();

        //3.1 用户全局门票放入CAS端的cookie中
        setCookie(COOKIE_USER_TICKET, userTicket, response);

        //4.userTicket关联用户id，并且放入到redis中，代表这个用户拥有门票，可以登录各个系统
        redisOperator.set(REDIS_USER_TICKET + ":" + userTicket, user.getId());

        //5.生成临时票据，回跳到调用端网址，是由CAS端所签发的一个一次性的临时ticket
        String tmpTicket = createTmpTicket();

        /**
         * userTicket: 用户标识用户在CAS端的一个登陆状态：已经登陆
         * tmpTicket(微信和支付宝称为—CODE): 用户进行一次性的验证的票据，有时效性
         */

        /**
         * 举例：
         *      我们去动物园玩耍，大门口买了一张统一的门票，这个就是CAS的全局门票和用户全局会话
         *      动物园里有一些小景点需要凭门票领取一次性的票据，有了这张票据以后就能去一些小的景点游玩
         *      这样的一个个的小景点就是我们这里所对应的一个个的站点。
         *      当我们使用完毕这张临时票据以后，需要销毁。
         */


        //return "login";
        return "redirect:" + returnUrl + "?tmpTicket=" + tmpTicket;
    }


    /**
     * @param tmpTicket
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/verifyTmpTicket")
    @ResponseBody
    public HttpResult verifyTmpTicket(String tmpTicket,
                                      HttpServletRequest request,
                                      HttpServletResponse response) {

        // 使用一次性临时票据来验证用户是否登陆，如果登陆过，将用户会话信息返回给站点
        // 使用完毕后，需要销毁临时票据
        String tmpTicketValue = redisOperator.get(REDIS_TMP_TICKET + ":" + tmpTicket);
        if (StringUtils.isBlank(tmpTicketValue)) {
            return HttpResult.errorUserTicket("用户票据异常");
        }

        //0.如果临时票据OK，则需要销毁，并且拿到CAS端的cookie中的全局userTicket，以此再获取用户会话
        try {
            if (!tmpTicketValue.equals(MD5Utils.getMD5Str24(tmpTicket))) {
                return HttpResult.errorUserTicket("用户票据异常");
            } else {
                //销毁临时票据
                redisOperator.del(REDIS_TMP_TICKET + ":" + tmpTicket);
            }

            //1.验证并且获取userTicket
            String userTicket = getCookie(COOKIE_USER_TICKET, request);
            String userId = redisOperator.get(REDIS_USER_TICKET + ":" + userTicket);
            if (StringUtils.isBlank(userId)) {
                return HttpResult.errorUserTicket("用户票据异常");
            }
            //2.验证门票对应的user会话是否存在
            String userRedis = redisOperator.get(REDIS_USER_TICKET + ":" + userId);
            if (StringUtils.isBlank(userRedis)) {
                return HttpResult.errorUserTicket("用户票据异常");
            }
            //3.验证成功，返回OK，携带用户会话
            return HttpResult.ok(JsonUtils.jsonToPojo(userRedis, UsersVO.class));

        } catch (Exception e) {
            e.printStackTrace();
        }

        return HttpResult.ok();
    }


    @PostMapping("/logout")
    @ResponseBody
    public HttpResult logout(String userId,
                             HttpServletRequest request,
                             HttpServletResponse response) {
        //0.获取CAS中的用户门票
        String userTicket = getCookie(COOKIE_USER_TICKET, request);

        //1.清除userTicket票据，reids/Cookie
        delCookie(COOKIE_USER_TICKET, response);
        redisOperator.del(REDIS_USER_TICKET + ":" + userId);

        //2.清除用户全局会话(分布式会话)
        redisOperator.del(REDIS_USER_TOKEN + ":" + userId);

        return HttpResult.ok();
    }

    /**
     * 创建临时票据
     *
     * @return
     */
    private String createTmpTicket() {

        String tmpTicket = UUID.randomUUID().toString().trim();
        try {
            redisOperator.set(REDIS_TMP_TICKET + ":" + tmpTicket,
                    MD5Utils.getMD5Str24(tmpTicket), 600);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tmpTicket;
    }

    /**
     * 设置Cookie
     *
     * @param key
     * @param value
     * @param response
     */
    private void setCookie(String key, String value, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, value);
        cookie.setDomain("sso.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }


    private void delCookie(String key, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, null);
        cookie.setDomain("sso.com");
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }

    /**
     * 获取Cookie
     *
     * @param key
     * @param request
     * @return
     */
    private String getCookie(String key, HttpServletRequest request) {

        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || StringUtils.isBlank(key)) {
            return null;
        }
        String cookieValue = null;
        for (int i = 0; i < cookieList.length; i++) {
            if (cookieList[i].getName().equals(key)) {
                cookieValue = cookieList[i].getValue();
                break;
            }
        }
        return cookieValue;
    }
}
